package com.cloud.codegenerator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * MyBatisPlus 代码生成器
 */
public class DomainGeneratorLocal {
    private static final String DRIVER_NAME ="com.mysql.jdbc.Driver";
    private static final String DB_CONN_STR = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "root";
    private static final String BASE_PACKAGE = "com.cloud.code.generator";
    private static final String SERVICE_SRC_MAIN = "spring-boot-starter-code-generator/src/main";
    private static final String[] REMOVE_PREFIX = {"view_"};
    private static final String TABLES = "area_new1|area_new2";

    public static void main(String[] args) throws IOException {
        // 工程根目录
        String projectRoot = new File(".").getCanonicalPath();
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        Path path = FileSystems.getDefault().getPath(projectRoot, SERVICE_SRC_MAIN, "java");

        gc.setOutputDir(path.normalize().toString());
        gc.setAuthor("MBP Generator");
        gc.setOpen(false);
        // 日期类型使用java.util.Date
        gc.setDateType(DateType.ONLY_DATE);
        // 文件覆盖
        gc.setFileOverride(true);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        gc.setServiceName("%sService");
        gc.setActiveRecord(false);

        // XML 二级缓存
        gc.setEnableCache(false);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        configDataSource(mpg);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(BASE_PACKAGE);
        // 实体类的包名
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return FileSystems.getDefault().getPath(projectRoot,
                        SERVICE_SRC_MAIN, "/resources/mapper/",
                        tableInfo.getEntityName() + "Mapper.xml").toString();
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 代码生成模板配置
        configTemplate(mpg);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setSuperEntityClass(Model.class);
        strategy.setChainModel(true);
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setEnableSqlFilter(false); // 设置了false之后include可用正则
        strategy.setInclude(TABLES);
        // 逻辑删除字段名
        strategy.setLogicDeleteFieldName("is_deleted");
        // 自动填充
        configTableFill(strategy);
        strategy.setEntityTableFieldAnnotationEnable(true);
        strategy.setEntityColumnConstant(false);
        // 设置prefix之后，类名会去掉这个前缀，Entity的注解会加上@TableName
        strategy.setTablePrefix(REMOVE_PREFIX);
        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

    private static void configDataSource(AutoGenerator mpg) {
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDriverName(DRIVER_NAME);
        dsc.setUrl(DB_CONN_STR);
        dsc.setUsername(DB_USER);
        dsc.setPassword(DB_PASSWORD);
        mpg.setDataSource(dsc);
    }

    private static void configTemplate(AutoGenerator mpg) {
        TemplateConfig templateConfig = new TemplateConfig();
        // 设置是否需要在mapper接口相同package生成xml映射文件
        templateConfig.setXml(null);
        // 不生成控制器
        templateConfig.setController(null);
        // 不生成Service类
        templateConfig.setService(null);
        templateConfig.setServiceImpl(null);
        // 可以指定模板资源路径
        // templateConfig.setEntity(null);
        mpg.setTemplate(templateConfig);
    }

    private static void configTableFill(StrategyConfig strategy) {
        List<TableFill> tableFillList = new ArrayList<>();
        tableFillList.add(new TableFill("gmt_created", FieldFill.INSERT));
        tableFillList.add(new TableFill("gmt_modified", FieldFill.INSERT_UPDATE));
        tableFillList.add(new TableFill("is_deleted", FieldFill.INSERT));
        tableFillList.add(new TableFill("deleted_time", FieldFill.INSERT));
        strategy.setTableFillList(tableFillList);
    }

}
